<template>
  <div class="wrapper">
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>花呗管理</p>
    </header>
    <div class="content" v-if="wallet">
      <!-- 花呗概览 -->
      <div class="section overview">
        <div class="title">花呗概览</div>
        <div class="overview-grid">
          <div class="overview-item">
            <div class="label">授信额度</div>
            <div class="value">{{ formatCurrency(wallet.overdraftLimit || 0) }}</div>
          </div>
          <div class="overview-item">
            <div class="label">已用额度</div>
            <div class="value used">{{ formatCurrency(wallet.userOverdraft || 0) }}</div>
          </div>
          <div class="overview-item">
            <div class="label">可用额度</div>
            <div class="value available">{{ formatCurrency(availableOverdraft) }}</div>
          </div>
        </div>
        <div class="status-badge" :class="statusClass">
          <span>{{ statusText }}</span>
        </div>
      </div>

      <!-- 操作选项（仅管理员可见） -->
      <div class="section" v-if="isAdmin">
        <div class="title">操作类型</div>
        <div class="options">
          <label>
            <input type="radio" value="set" v-model="operationType" />
            <span>设置额度</span>
          </label>
          <label>
            <input type="radio" value="increase" v-model="operationType" />
            <span>增加额度</span>
          </label>
          <label>
            <input type="radio" value="decrease" v-model="operationType" />
            <span>减少额度</span>
          </label>
        </div>
      </div>

      <!-- 金额输入（仅管理员可见） -->
      <div class="section" v-if="isAdmin">
        <div class="title">操作金额</div>
        <div class="presets">
          <button v-for="p in presets" :key="p" :class="{active: amount===p}" @click="amount=p">¥{{ p }}</button>
        </div>
        <input type="number" v-model.number="amount" :placeholder="operationPlaceholder" @input="validateAmount" />
        <div v-if="amountError" class="error-msg">{{ amountError }}</div>
        <div v-if="operationType === 'decrease' && amount > 0" class="info-msg">
          减少后额度：{{ formatCurrency(Math.max(0, (wallet.overdraftLimit || 0) - amount)) }}
        </div>
      </div>

      <!-- 备注（仅管理员可见） -->
      <div class="section" v-if="isAdmin">
        <div class="title">备注说明</div>
        <textarea v-model="remark" placeholder="请输入备注信息（可选）" rows="3"></textarea>
      </div>

      <!-- 确认按钮（仅管理员可见） -->
      <div class="section" v-if="isAdmin">
        <button class="confirm" :disabled="!canSubmit" @click="confirmOperation">确认{{ operationText }}</button>
      </div>

      <!-- 普通用户提示 -->
      <div class="section" v-if="!isAdmin">
        <div class="info-box">
          <div class="info-title">📌 提示</div>
          <div class="info-content">
            普通用户的花呗额度由系统统一设置为1000元，无法自行调整。如需修改额度，请联系管理员。
          </div>
        </div>
      </div>

      <!-- 操作结果 -->
      <div v-if="lastResult" class="result">
        <div class="result-title">操作成功</div>
        <div>当前授信额度：{{ formatCurrency(lastResult.overdraftLimit || 0) }}</div>
        <div>已用额度：{{ formatCurrency(lastResult.userOverdraft || 0) }}</div>
        <div>可用额度：{{ formatCurrency((lastResult.overdraftLimit || 0) - (lastResult.userOverdraft || 0)) }}</div>
      </div>
    </div>
    <div v-else class="loading">加载中...</div>
    <Footer />
  </div>
</template>

<script setup>
import Footer from '../components/Footer.vue'
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { walletApi, userApi } from '../api'

const router = useRouter()
const wallet = ref(null)
const currentUser = ref(null)
const operationType = ref('set')
const amount = ref(0)
const remark = ref('')
const amountError = ref('')
const lastResult = ref(null)
const presets = [100, 200, 500, 1000]

const loadWallet = async () => {
  try {
    const [user, w] = await Promise.all([
      userApi.getCurrentUser(),
      walletApi.getMyWallet()
    ])
    currentUser.value = user
    wallet.value = w
    lastResult.value = null
  } catch (e) {
    console.error('加载钱包信息失败:', e)
  }
}

// 判断是否为管理员
const isAdmin = computed(() => {
  return currentUser.value?.authorities?.some(auth => auth.name === 'ADMIN') || false
})

onMounted(() => {
  loadWallet()
})

const formatCurrency = v => {
  const n = Number(v || 0)
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + '元'
}

const availableOverdraft = computed(() => {
  if (!wallet.value) return 0
  const limit = Number(wallet.value.overdraftLimit || 0)
  const used = Number(wallet.value.userOverdraft || 0)
  return Math.max(0, limit - used)
})

const statusText = computed(() => {
  if (!wallet.value) return '正常'
  const used = Number(wallet.value.userOverdraft || 0)
  if (used > 0) return '使用中'
  return '正常'
})

const statusClass = computed(() => {
  if (!wallet.value) return 'status-normal'
  const used = Number(wallet.value.userOverdraft || 0)
  if (used > 0) return 'status-active'
  return 'status-normal'
})

const operationPlaceholder = computed(() => {
  const map = {
    set: '请输入要设置的花呗额度',
    increase: '请输入要增加的额度',
    decrease: '请输入要减少的额度'
  }
  return map[operationType.value] || '请输入金额'
})

const operationText = computed(() => {
  const map = {
    set: '设置',
    increase: '增加',
    decrease: '减少'
  }
  return map[operationType.value] || '操作'
})

const validateAmount = () => {
  amountError.value = ''
  if (!amount.value || amount.value <= 0) {
    amountError.value = '请输入有效的金额'
    return false
  }
  if (operationType.value === 'decrease') {
    const currentLimit = Number(wallet.value?.overdraftLimit || 0)
    if (amount.value > currentLimit) {
      amountError.value = `减少金额不能超过当前额度 ${formatCurrency(currentLimit)}`
      return false
    }
  }
  return true
}

const canSubmit = computed(() => {
  if (!amount.value || amount.value <= 0) return false
  if (amountError.value) return false
  return true
})

const confirmOperation = async () => {
  if (!validateAmount()) return

  try {
    let result
    const params = {
      amount: amount.value,
      remark: remark.value || `${operationText.value}花呗额度`
    }

    switch (operationType.value) {
      case 'set':
        result = await walletApi.setOverdraftLimit(params)
        break
      case 'increase':
        result = await walletApi.increaseOverdraftLimit(params)
        break
      case 'decrease':
        result = await walletApi.decreaseOverdraftLimit(params)
        break
    }

    if (result) {
      lastResult.value = result
      await loadWallet()
      // 清空表单
      amount.value = 0
      remark.value = ''
      amountError.value = ''
    }
  } catch (e) {
    amountError.value = e.message || '操作失败，请重试'
    console.error('操作失败:', e)
  }
}

const goBack = () => router.push('/wallet')
</script>

<style scoped>
.wrapper { width: 100%; min-height: 100%; }
header { width: 100%; height: 12vw; background-color: #0097ff; color: #fff; font-size: 4.8vw; position: fixed; left: 0; top: 0; z-index: 1000; display: flex; justify-content: center; align-items: center; }
header i { position: absolute; left: 3vw; font-size: 6vw; color: #fff; cursor: pointer; }
.content { margin-top: 14vw; padding: 4vw; }
.loading { margin-top: 14vw; padding: 4vw; text-align: center; color: #666; }

.section { background: #fff; border-radius: 2vw; padding: 4vw; margin-bottom: 4vw; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
.title { font-size: 4.2vw; font-weight: 600; color: #333; margin-bottom: 3vw; }

.overview { }
.overview-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 3vw; margin-bottom: 3vw; }
.overview-item { text-align: center; }
.overview-item .label { font-size: 3.2vw; color: #666; margin-bottom: 1.5vw; }
.overview-item .value { font-size: 4.5vw; font-weight: 700; color: #333; }
.overview-item .value.used { color: #ff6b35; }
.overview-item .value.available { color: #38ca73; }
.status-badge { display: inline-block; padding: 1.5vw 3vw; border-radius: 1.5vw; font-size: 3.4vw; font-weight: 500; }
.status-badge.status-normal { background: #e8f5e9; color: #2e7d32; }
.status-badge.status-active { background: #fff3e0; color: #e65100; }

.options { display: flex; flex-direction: column; gap: 2.5vw; }
.options label { display: flex; align-items: center; gap: 2vw; font-size: 3.8vw; cursor: pointer; }
.options input[type="radio"] { width: 4.5vw; height: 4.5vw; cursor: pointer; }

.presets { display: grid; grid-template-columns: repeat(4, 1fr); gap: 2vw; margin-bottom: 3vw; }
.presets button { height: 9vw; border: 1px solid #ddd; border-radius: 2vw; background: #fff; font-size: 3.6vw; color: #333; cursor: pointer; transition: all .2s ease; }
.presets button.active { background: #0097ff; color: #fff; border-color: #0097ff; }
.presets button:hover { border-color: #0097ff; }

input[type="number"] { width: 100%; height: 10vw; border: 1px solid #ddd; border-radius: 2vw; padding: 0 3vw; font-size: 4vw; box-sizing: border-box; }
input[type="number"]:focus { outline: none; border-color: #0097ff; }

textarea { width: 100%; border: 1px solid #ddd; border-radius: 2vw; padding: 3vw; font-size: 3.8vw; box-sizing: border-box; resize: vertical; font-family: inherit; }
textarea:focus { outline: none; border-color: #0097ff; }

.error-msg { margin-top: 2vw; color: #ff5252; font-size: 3.4vw; }
.info-msg { margin-top: 2vw; color: #666; font-size: 3.4vw; }

.confirm { width: 100%; height: 11vw; border: none; border-radius: 2vw; background: #0097ff; color: #fff; font-size: 4.2vw; font-weight: 500; cursor: pointer; transition: background .2s ease; }
.confirm:hover:not(:disabled) { background: #0088e6; }
.confirm:disabled { background: #ccc; cursor: not-allowed; }

.result { background: #e8f5e9; border-radius: 2vw; padding: 4vw; margin-top: 4vw; }
.result-title { font-size: 4.5vw; font-weight: 600; color: #2e7d32; margin-bottom: 2vw; }
.result div { font-size: 3.8vw; color: #333; margin-top: 1.5vw; }

.info-box { background: #e3f2fd; border-left: 3px solid #2196f3; padding: 3vw; border-radius: 2vw; }
.info-title { font-size: 4vw; font-weight: 600; color: #1976d2; margin-bottom: 2vw; }
.info-content { font-size: 3.6vw; color: #555; line-height: 1.6; }
</style>

